package cn.huiyunche.base.service.interfaces.impl;

import cn.huiyunche.base.service.enums.BFeeModelEnum;
import cn.huiyunche.base.service.enums.BFeeTypeEnum;
import cn.huiyunche.base.service.interfaces.BFeeModelService;
import cn.huiyunche.base.service.interfaces.BFeeTypeService;
import cn.huiyunche.base.service.interfaces.SInvoiceRateService;
import cn.huiyunche.base.service.interfaces.SOrderFeeDetailService;
import cn.huiyunche.base.service.model.BFeeType;
import cn.huiyunche.base.service.model.SInvoiceRate;
import cn.huiyunche.base.service.vo.SOrderFeeDetailVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.Arrays;

@Service
public class SInvoiceRateServiceImpl implements SInvoiceRateService {

    private static final Logger LOGGER = LoggerFactory.getLogger(SInsuranceFeeServiceImpl.class);

    @Autowired
    private BFeeModelService bFeeModelService;

    @Autowired
    private BFeeTypeService bFeeTypeService;

    @Autowired
    private SOrderFeeDetailService sOrderFeeDetailService;

    @Override
    public SOrderFeeDetailVo computeInvoiceFee(Boolean hasInvoiceFee, Long customerOrderId, BigDecimal totalCost) {
        LOGGER.info("computeInvoiceFee params : {}", hasInvoiceFee, totalCost);
        if (null == hasInvoiceFee) {
            LOGGER.info("computeInvoiceFee hasInvoiceFee is null");
            hasInvoiceFee = false;
        }
        if (null == totalCost) {
            LOGGER.info("computeInvoiceFee totalCost is null");
            totalCost = BigDecimal.ZERO.setScale(2);
        }

        // 总发票费
        BigDecimal total = BigDecimal.ZERO.setScale(2);

        //查询费用类型信息
        BFeeType feeType = bFeeTypeService.getByCode(bFeeModelService.getByCode(BFeeModelEnum.INTERCITY_ORDER).getId(), Arrays.asList(BFeeTypeEnum.INVOICE_TAX.getValue())).get(0);

        SInvoiceRate invoiceRate = new SInvoiceRate();
        invoiceRate.setRate(BigDecimal.ZERO);
        if (hasInvoiceFee) {
            invoiceRate = bFeeTypeService.getSIvoiceRateByFeeCode(feeType.getId());
            total = totalCost.multiply(invoiceRate.getRate()).setScale(0, RoundingMode.UP).setScale(2);

            if (null != customerOrderId) {
                // 保存费用详情
                sOrderFeeDetailService.addFeeDetail(customerOrderId, feeType.getId(), feeType.getFeeCode(), feeType.getFeeName(), total, total);
            }
        }

        SOrderFeeDetailVo vo = new SOrderFeeDetailVo();
        vo.setId(feeType.getId());
        vo.setFeeCode(feeType.getFeeCode());
        vo.setFeeName(feeType.getFeeName());
        vo.setCost(total);
        vo.setActualAmount(total);
        vo.setDiscount(total);

        return vo;
    }

}

